//
//  HomeTableViewController.swift
//  Weibo10
//
//  Created by male on 15/10/14.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD

// 原创微博可重用表示符号
let StatusCellNormalId = "StatusCellNormalId"
// 转发微博的可重用表示符
let StatusRetweetedCellId = "StatusRetweetedCellId"

class HomeTableViewController: VisitorTableViewController {

    // 懒加载微博列表模型
    private lazy var listViewModel = StatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 如果登录成功显示下面的 label 否则执行下面的代码
        if !UserAccountViewModel.sharedUserAccount.userLogon {
        
            visitorView?.setupInfo(nil, title: "关注一些人，回这里看看有什么惊喜")
            return
        }
        
        prepareTableVie()
        
        loadData()
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserverForName(WBStatusSelectedPhotoNotification,
            object: nil,
            queue: nil) {[weak self](n) -> Void in
                
                guard let urls = n.userInfo?[WBStatusSelectedPhotoURLsKey] as? [NSURL] else {
                    return
                }
                
                guard let indexPath = n.userInfo?[WBStatusSelectedPhotoIndexPathKey] as? NSIndexPath else{
                    return
                }
                
                guard let cell = n.object as? PhotoBrowserPresentDelegate else {
                    return
                }
                
                print("选择 照片 cell \(cell)")
                
                let vc = PhotoBrowserViewController(urls: urls, indexPath: indexPath)
                
                // 1. 设置modal的类型是自定义类型Transition(转场)
                vc.modalPresentationStyle = UIModalPresentationStyle.Custom
                
                // 2. 设置动画代理
                vc.transitioningDelegate = self?.photoBrowserAnimatot
                
                // 设置 animator 的代理参数
                self?.photoBrowserAnimatot.setDelegateParame(cell, indexPath: indexPath, dismissDelegate: vc)
                
                // 3. Modal
                self?.presentViewController(vc, animated: true, completion: nil)
                
                // print("接收通知 \(urls) ")
               // print("打印\(indexPath)")
        }
    }
    
    // 注销通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // 准备表格
    private func prepareTableVie() {
        // 注册可重用cell
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: StatusCellNormalId)
        tableView.registerClass(StatusRetweetedCell.self, forCellReuseIdentifier: StatusRetweetedCellId)
        
        // 取消分割线
        tableView.separatorStyle = .None
        
        // 测试行高
        tableView.estimatedRowHeight = 400
        
        refreshControl = WBRefreshControl()
       // refreshControl?.backgroundColor = UIColor.redColor()
        
        // 添加监听方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        // 上拉刷新视图
        tableView.tableFooterView = pullupView
        
        //refreshControl?.tintColor = UIColor.clearColor()
        
    }
    
/// 加载网络数据
    @objc private func loadData() {
        
        self.refreshControl?.beginRefreshing()
        
        listViewModel.loadStatus (isPullup: pullupView.isAnimating()){ (isSuccessed) -> () in
            
            self.refreshControl?.endRefreshing()
            self.pullupView.stopAnimating()
            
            if !isSuccessed {
                SVProgressHUD.showInfoWithStatus("数据加载错误,请稍等")
                return
            }
            
           // print(self.listViewModel.statusList)
            
            // 刷新数据
            self.tableView.reloadData()
        }
    }

/// MARK: - 懒加载上啦刷新控件
private lazy var pullupView: UIActivityIndicatorView = {
    
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
    
        indicator.color = UIColor.darkGrayColor()
    
        return indicator

    }()
    
    /// MARK: - 照片查看转场动画代理
    private lazy var photoBrowserAnimatot: PhotoBrowserAnimator = PhotoBrowserAnimator()
}

// MARK: -数据源方法
extension HomeTableViewController {

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return listViewModel.statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let vm = listViewModel.statusList[indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(vm.cellId, forIndexPath: indexPath) as! StatusCell
        
        cell.viewModel = vm
        
        // 判断是否是最后一条微博
        if indexPath.row == listViewModel.statusList.count - 1 && !pullupView.isAnimating() {
        
            // 开始动画
            pullupView.startAnimating()
            
            
            loadData()
            print("上啦刷新数据")
        }
        
        return cell
    }
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        return listViewModel.statusList[indexPath.row].rowHeight
            }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("选中行 \(indexPath)")
    }
}
